package com.sinoyd.itszyw.Fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.sinoyd.itszyw.Activity.LoginActivity;
import com.sinoyd.itszyw.Dialog.DownloadDialog;
import com.sinoyd.itszyw.Model.VersionUpdate;
import com.sinoyd.itszyw.R;
import com.sinoyd.itszyw.Util.PreferencesUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import static com.sinoyd.itszyw.MyApplication.GetVersion;
import static com.sinoyd.itszyw.MyApplication.VERSION_DATA;
import static com.sinoyd.itszyw.MyApplication.versionName;

/**
 * @createBy : Sinoyd 大饼洲
 * @description :
 * @projectName : ITYW
 * @creationDate: 2017-04-01 14:42
 */
@ContentView(R.layout.fragment_more)
public class MoreFragment extends BaseFragment {

    @ViewInject(R.id.txt_title)
    private TextView txt_title;
    @ViewInject(R.id.more_version_details)
    TextView more_version_details;

    private int GET_VERSION = 111;
    private final int CODE_FOR_WRITE_PERMISSION = 1;


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        txt_title.setText(this.getResources().getString(R.string.more_more));
        more_version_details.setText(versionName);
    }

    private void setVersionView() {

        RequestParams params = new RequestParams(GetVersion);
        params.addQueryStringParameter("validation","sinoyd123!@#");
        try {
            sendHttpRequest(params, HttpMethod.GET, GET_VERSION);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }




    public void getVerion() {
        if (VERSION_DATA.VerCode != null) {
            if (Double.parseDouble(versionName) < Double.parseDouble(VERSION_DATA.VerCode)) {

                AlertDialog.Builder versiondialog = new AlertDialog.Builder(
                        getActivity(),
                        AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

                versiondialog.setTitle("版本更新");
                versiondialog.setMessage("当前版本" + versionName
                        + "\n" + "发现新版本" + VERSION_DATA.VerCode
//                            + "。\n更新内容：" + VERSION_DATA.VerValue
                        + "\n" + "是否更新新版本");
                versiondialog.setPositiveButton("立即更新",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(
                                    DialogInterface paramDialogInterface,
                                    int paramInt) {
                                DownloadDialog.Builder builder = new DownloadDialog.Builder(
                                        getActivity());
                                builder.create().show();
                            }
                        });
                versiondialog.setNegativeButton("暂不更新",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(
                                    DialogInterface paramDialogInterface,
                                    int paramInt) {
                                paramDialogInterface.dismiss();
                            }
                        });
                versiondialog.show();

            } else {
                showToast("当前为最新版本！");
            }
        } else {
        }
    }



    @Event({R.id.more_version_new,R.id.more_help,R.id.more_go_out})
    private void getOnclick(View view){
        switch (view.getId()){
            case R.id.more_version_new:

                if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //如果没有授权，则请求授权
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_FOR_WRITE_PERMISSION);
                } else {
                    //有授权，直接询问是否下载
                    setVersionView();

                }

                break;
            case R.id.more_help:
                showToast("暂无帮助信息");
                break;
            case R.id.more_go_out:

                PreferencesUtils.putString(getActivity(), "account", "");
                PreferencesUtils.putString(getActivity(), "password", "");
                PreferencesUtils.putBoolean(getActivity(), "accountBoolean", false);
                PreferencesUtils.putBoolean(getActivity(), "passwordBoolean", false);
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void httpOnSuccess(String responseStr, int requestCode) {
        if (requestCode == GET_VERSION) {
            try {
                JSONObject objJSON = new JSONObject(responseStr);

                if (objJSON.getBoolean("IsSuccess")){
                    JSONObject object = objJSON.getJSONArray("Data").getJSONObject(0);
                    VERSION_DATA  = new VersionUpdate(object);
                    getVerion();
                }else{
                    showToast("获取版本失败~");
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == CODE_FOR_WRITE_PERMISSION){
            if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    &&grantResults[0] == PackageManager.PERMISSION_GRANTED){
                //用户同意使用write
                setVersionView();
            }else{
                //用户不同意，自行处理即可
                //授权失败
                Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

}
